package com.boolib.service.impl;

import com.boolib.commons.Const;
import com.boolib.commons.entity.ServerResponse;
import com.boolib.load.mail.IMailService;
import com.boolib.commons.util.PasswordUtil;
import com.boolib.commons.util.ServerResponseUtil;
import com.boolib.commons.util.UUIDUtil;
import com.boolib.dao.ShopUserMapper;
import com.boolib.pojo.ShopUser;
import com.boolib.pojo.SysUser;
import com.boolib.service.IUserService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {



    @Value("${mail.from}")
    private String fromMail ;


    @Value("${mail.title}")
    private String  mailTitle;


    @Autowired
    private IMailService mailService;




    @Autowired
    private ShopUserMapper shopUserMapper;


    /**
     * 用户注册
     * @param shopUser
     * @return
     */
    @Override
    public ServerResponse<ShopUser> ShopUserRegister(ShopUser shopUser) {

        ServerResponse t = checkArgumentNull(shopUser);

        if(!t.isSuccess()) return  t;

        //查询是否有重名的,不查状态信息， 直接查重复名
        ShopUser temp  =  new ShopUser();

        temp.setUsername(shopUser.getUsername());


        ShopUser shopUser1 = shopUserMapper.selectOne(temp);


        /**
         * 用户存在说明不能注册 返回已存在状态信息
         */
        if(shopUser1!= null)
            return  ServerResponse.createByError(
                    Const.User.Status.USEREXIST.getCode(),
                Const.User.Status.USEREXIST.getMessage()
            );


        /**
         * 检测email是否重复
         */
        ServerResponse serverResponse =checkEmail(shopUser.getEmail());


        if(!serverResponse.isSuccess()){
            return serverResponse;
        }


        /**
         *
         * 检测手机号是否重复
         */
        serverResponse = checkPhone(shopUser.getPhonenumber());


        if(!serverResponse.isSuccess()){
            return serverResponse;
        }


        //生成salt

        String salt = UUIDUtil.getUUID();


        //获取密码
        String pass = shopUser.getPassword();




        StringBuffer buffer  = new StringBuffer();

        //密码加盐处理
        String encryptPass = PasswordUtil.getEncryptPass2(pass,salt);


        shopUser.setSalt(salt);

        shopUser.setPassword(encryptPass);


        Date date = new Date();

        shopUser.setAvatar(null);

        shopUser.setDelFlag(null);

        shopUser.setLoginDate(null);

        shopUser.setLoginIp(null);

        shopUser.setUserType(Const.User.ISUSER);

        shopUser.setStatus(null);


        shopUser.setUpdateTime(date);

        shopUser.setCreateTime(date);

        /**
         * 新增用户
         */
       if( shopUserMapper.insertSelective(shopUser)>0){
           return  ServerResponse.createBySuccessMessage(
                   Const.User.Status.REGISTERSUCCESS.getMessage()
           );
       }





        return ServerResponse.createByError(
                Const.User.Status.REGISTERFAILD.getCode(),
                Const.User.Status.REGISTERFAILD.getMessage()
        );
    }










    @Override
    public ServerResponse<ShopUser> ShopUserLoginAuth(ShopUser shopUser) {


        /**
         * 判断是否为空
         */
       ServerResponse serverResponse =  ServerResponseUtil.argumentCheck(shopUser.getUsername(),shopUser.getPassword());

       if(!serverResponse.isSuccess()) return  serverResponse;

        ShopUser temp = new ShopUser();

        temp.setUsername(shopUser.getUsername());

        ShopUser resultUser =  shopUserMapper.selectOne(temp);

       serverResponse = checkUserState(resultUser);

        if(!serverResponse.isSuccess()) return serverResponse;


        String salt = resultUser.getSalt();

        String encryptPass = PasswordUtil.getEncryptPass2(shopUser.getPassword(),salt);

        if(!encryptPass.equals(resultUser.getPassword())){
            return ServerResponse.createByError(Const.User.Status.PASSWORDFAILD.getCode()
                    ,Const.User.Status.PASSWORDFAILD.getMessage());
        }

        resultUser.setSalt(Strings.EMPTY);

        resultUser.setPassword(Strings.EMPTY);

        ShopUser up = new ShopUser();
        up.setId(resultUser.getId());

        up.setLoginDate(new Date());

        shopUserMapper.updateByPrimaryKeySelective(up);

        return ServerResponse.createBySuccess(resultUser);
    }

    @Override
    public ServerResponse<ShopUser> ShopUserLogout(HttpSession session) {

        ShopUser shopUser = (ShopUser) session.getAttribute(Const.User.SESSIONAUTH);

        if(shopUser == null) return  ServerResponse.createByError(Const.System.Status.UNAUTHENTICATION.getCode(),Const.System.Status.UNAUTHENTICATION.getMessage());

        session.removeAttribute(Const.User.SESSIONAUTH);

        return ServerResponse.createBySuccessMessage("退出成功");
    }

    @Override
    public ServerResponse ShopUserForgetPassword(String username) {

        if(Strings.isBlank(username)) return  ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),Const.System.Status.ARGUMENTNULL.getMessage());


        ShopUser  temp = new ShopUser();

        temp.setUsername(username);

        ShopUser resultUser = shopUserMapper.selectOne(temp);

        ServerResponse serverResponse = checkUserState(resultUser);


        if(!serverResponse.isSuccess()){
            return  serverResponse;
        }

        String email = resultUser.getEmail();

        if(Strings.isBlank(email)){
            return ServerResponse.createByError(Const.User.Status.UNBINDMAIL.getCode(),Const.User.Status.UNBINDMAIL.getMessage());
        }


        mailService.sendForgetMail(fromMail,email,mailTitle,resultUser.getId());

        Map map = Maps.newHashMap();

        map.put("userId",resultUser.getId());

        return ServerResponse.createBySuccess(Const.User.ALTERPASSWORDURL+"/"+resultUser.getId());
    }

    @Override
    public ServerResponse ShopUserAlterPasswordBeforeLogin(Integer id, String password, String code) {


        ServerResponse serverResponse = ServerResponseUtil.argumentCheck(id,password,code);

        if(!serverResponse.isSuccess()) return  serverResponse;

        serverResponse = mailService.checkMailToken(id,code);

        if(!serverResponse.isSuccess()) return serverResponse;

        serverResponse    = checkUserExistById(id);

        if(!serverResponse.isSuccess()) return serverResponse;

        ShopUser temp = (ShopUser) serverResponse.getData();

        String salt =   temp.getSalt();

        String encryptPass = PasswordUtil.getEncryptPass2(password,salt);


        ShopUser update =  new ShopUser();

        update.setId(id);

        update.setPassword(encryptPass);

        update.setUpdateTime(new Date());

        if(shopUserMapper.updateByPrimaryKeySelective(update)>0)
            return ServerResponse.createBySuccessMessage("密码更新成功");
        return ServerResponse.createByErrorMessage("更新失败");

    }

    @Override
    public ServerResponse ShopUserAlterPasswordAfterLogin(Integer id, String password) {

        ServerResponse serverResponse = ServerResponseUtil.argumentCheck(id,password);

        if(!serverResponse.isSuccess()) return  serverResponse;

        serverResponse = checkUserExistById(id);

        if(!serverResponse.isSuccess()) return serverResponse;

        ShopUser shopUser = (ShopUser) serverResponse.getData();


        serverResponse =   checkUserState(shopUser);

        if(!serverResponse.isSuccess()) return serverResponse;


        String encryptPass= PasswordUtil.getEncryptPass2(password,shopUser.getSalt());


        ShopUser temp = new ShopUser();


        temp.setId(id);

        temp.setPassword(encryptPass);
        temp.setUpdateTime(new Date());


     if(   shopUserMapper.updateByPrimaryKeySelective(temp)>0){
         return  ServerResponse.createBySuccessMessage("更新成功");
     }


        return ServerResponse.createByErrorMessage("更新失败");
    }

    @Override
    public ServerResponse ShopUserAlterAvatar(Integer id, String avatar) {

        if(id == null ||Strings.isBlank(avatar)) return  ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),Const.System.Status.ARGUMENTNULL.getMessage());

        ShopUser shopUser = new ShopUser();
        shopUser.setId(id);
        shopUser.setAvatar(avatar);
        shopUser.setUpdateTime(new Date());

        if(shopUserMapper.updateByPrimaryKeySelective(shopUser)>0){
            return  ServerResponse.createBySuccessMessage("头像更新成功");
        }

        return ServerResponse.createByErrorMessage("头像更新失败");
    }


    @Override
    public ServerResponse ShopUserAlterInfo(ShopUser shopUser) {

        shopUser.setUsername(null);

        shopUser.setPassword(null);

        shopUser.setCreateTime(null);


        shopUser.setUpdateTime(new Date());

        shopUser.setSalt(null);

        shopUser.setAvatar(null);

        shopUser.setLoginDate(null);

        shopUser.setStatus(null);

        shopUser.setUserType(null);

        shopUser.setDelFlag(null);

        shopUser.setRemark(null);

        if(!Strings.isBlank(shopUser.getEmail())){
            ServerResponse serverResponse =    checkEmail(shopUser.getEmail());
            if(!serverResponse.isSuccess())return serverResponse;
        }

        if(!Strings.isBlank(shopUser.getPhonenumber())){
            ServerResponse serverResponse =    checkPhone(shopUser.getPhonenumber());
            if(!serverResponse.isSuccess())return serverResponse;
        }
        if(shopUserMapper.updateByPrimaryKeySelective(shopUser)>0){
            ServerResponse.createBySuccessMessage("更新成功");
        }



        return    ServerResponse.createByErrorMessage("更新失败");
    }

    @Override
    public ServerResponse logout(HttpSession session) {

        String username = ((SysUser)session.getAttribute(Const.User.SESSIONAUTH)).getUsername();


        log.info("用户："+username+"，退出登录");

        session.removeAttribute(Const.User.SESSIONAUTH);
        return ServerResponse.createBySuccessMessage("用户退出成功");
    }


    /**
     * 私有方法
     */


    private ServerResponse checkUserState(ShopUser resultUser){
        if(resultUser == null )
            return ServerResponse.createByError(
                    Const.User.Status.USERNOTEXIST.getCode(),
                    Const.User.Status.USERNOTEXIST.getMessage()
            );

        if(resultUser.getDelFlag()>0){
            return ServerResponse.createByError(Const.User.Status.USERDEL.getCode()
                    ,Const.User.Status.USERDEL.getMessage());
        }

        if(resultUser.getStatus()>0){
            return ServerResponse.createByError(Const.User.Status.LOGINFAILD.getCode()
                    ,Const.User.Status.LOGINFAILD.getMessage());
        }


      return  ServerResponse.createBySuccess();

    }





    private  ServerResponse checkUserExistById(Integer id){
        ShopUser temp= new ShopUser();

        temp.setId(id);

        ShopUser result = shopUserMapper.selectOne(temp);

        if(result==null) return ServerResponse.createByError(Const.User.Status.USERNOTEXIST.getCode(),Const.User.Status.USERNOTEXIST.getMessage());

        return ServerResponse.createBySuccess(result);
    }

    private  ServerResponse checkUserExistByUserName(String username){
        ShopUser temp= new ShopUser();

        temp.setUsername(username);

        ShopUser result = shopUserMapper.selectOne(temp);

        if(result==null) return ServerResponse.createByError(Const.User.Status.USERNOTEXIST.getCode(),Const.User.Status.USERNOTEXIST.getMessage());

        return ServerResponse.createBySuccess(result);
    }


    private ServerResponse checkEmail(String email){

        ShopUser shopUser = new ShopUser();

        shopUser.setEmail(email);


        if(shopUserMapper.select(shopUser).size()>0)
        {
            return  ServerResponse.createByError(Const.User.Status.EMAILEXIST.getCode(),Const.User.Status.EMAILEXIST.getMessage());
        }
        return ServerResponse.createBySuccess();
    }


    private ServerResponse checkPhone(String phone){

        ShopUser shopUser = new ShopUser();

        shopUser.setPhonenumber(phone);


        if(shopUserMapper.select(shopUser).size()>0)
        {
            return  ServerResponse.createByError(Const.User.Status.PHONEEXIST.getCode(),Const.User.Status.PHONEEXIST.getMessage());
        }
        return ServerResponse.createBySuccess();
    }




    private  ServerResponse checkArgumentNull(ShopUser shopUser){


        if(shopUser.getEmail()==null || shopUser.getPassword() ==null || shopUser.getUsername()==null  || shopUser.getPassword()==null)
            return ServerResponse.createByError(Const.System.Status.ARGUMENTNULL.getCode(),
                    Const.System.Status.ARGUMENTNULL.getMessage());

        return ServerResponse.createBySuccess();
    }
}
